// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

import LuckyTurntable from "./luckyTurntable";
import {COMMON_CID} from "../web/model/UserModel";
import {model} from "../web/model/Model";
import {globalConfig} from "../config/globalConfig";
import {WordsUtils} from "../utils/wordsUtils";
import {apiUtils} from "../web/api/ApiUtils";
import {getItem, getReward, ResType} from "../config/config";
import {utils} from "../utils/utils";
import LuckyResult from "./luckyResult";
import {wxUtils} from "../wx/wxUtils";

const {ccclass, property} = cc._decorator;

@ccclass
export default class LuckyScene extends cc.Component {

  @property(cc.Node)
  luckTurntableNode: cc.Node = null

  @property(cc.Label)
  labelCoin: cc.Label = null

  @property(cc.Label)
  labelDiamond: cc.Label = null

  @property(cc.Label)
  labelPowerful: cc.Label = null

  @property(cc.Prefab)
  probabilityPrefab: cc.Prefab = null

  @property([cc.Label])
  costLabels: [cc.Label] = []

  @property(cc.Label)
  nameLabel: cc.Label = null

  @property(cc.Sprite)
  iconSprite: cc.Sprite = null

  @property(cc.Label)
  numLabel: cc.Label = null

  @property(cc.Label)
  totalLabel: cc.Label = null

  @property(cc.Node)
  btnSkin: cc.Node = null

  @property(cc.Node)
  btnMerge: cc.Node = null

  @property(cc.Node)
  luckyResult: cc.Node = null

  @property(cc.Sprite)
  powerfulSprite: cc.Sprite = null

  @property({type: cc.Texture2D})
  powerfulTexture: cc.Texture2D = null;

  @property(cc.Label)
  labelFreeCount: cc.Label = null;

  luckyTurntable: LuckyTurntable = null

  onLoad() {
    this.luckyTurntable = this.luckTurntableNode.getComponent(LuckyTurntable)
    model.user.bind(this.labelCoin, COMMON_CID.COIN)
    model.user.bind(this.labelDiamond, COMMON_CID.DIAMOND)
    this.refreshLabelPowerful()
    this.costLabels[0].string = `X${globalConfig.turntablecost.goldcost}`
    this.costLabels[1].string = `X${globalConfig.turntablecost.diamodscost}`
    this.luckyResult.active = false;
    this.refreshVideoCount();
    this.initSkinShow()
  }

  private refreshVideoCount() {
    this.labelFreeCount.string = `${model.user.msg.videoCount}/3`
  }

  onDestroy() {
    model.user.unbind(this.labelCoin)
    // model.user.unbind(this.labelPowerful)
    model.user.unbind(this.labelDiamond)
    model.user.unbind(this.numLabel)
  }

  private initSkinShow() {
    const rewardConfig: any = getReward(globalConfig.turntable[0].reward)
    const fragmentConfig: any = getItem(rewardConfig.itemid)
    const itemConfig: any = getItem(fragmentConfig.target)

    utils.setIcon(this.iconSprite, itemConfig.iconid, ResType.skinPiece)
    const fragmentCount = model.user.getItemNum(fragmentConfig.id)
    const mergeCount = itemConfig.number;

    this.btnMerge.active = false
    this.btnSkin.active = false
    if (fragmentCount + model.user.getItemNum(COMMON_CID.PIECE_POWERFUL) < mergeCount) {
      this.btnSkin.active = true
      model.user.bind(this.numLabel, fragmentConfig.id)
      this.totalLabel.string = `/${mergeCount}`
    } else {
      this.btnMerge.active = true
    }
    this.nameLabel.string = itemConfig.name
  }

  async onCoinRotateOnceTouch() {
    if (model.user.getItemNum(COMMON_CID.COIN) < globalConfig.turntablecost.goldcost) {
      return WordsUtils.error('金币不足')
    }
    const res = await apiUtils.luckyTurntable(1)
    await this.luckyTurntable.rotateOnceTo(res.index[0])
    this.showResult(res.index, false)
    this.initSkinShow()
    if (this.checkIsPowerful(res.index[0])) {
      this.flutterAction()
    }
  }

  async onDiamondRotateOnceTouch() {
    if (model.user.getItemNum(COMMON_CID.DIAMOND) < globalConfig.turntablecost.diamodscost) {
      return WordsUtils.error('钻石不足')
    }
    const res = await apiUtils.luckyTurntable(2);
    await this.luckyTurntable.rotateOnceTo(res.index[0])
    this.showResult(res.index)
    this.initSkinShow()
    if (this.checkIsPowerful(res.index[0])) {
      this.flutterAction()
    }
  }

  private isRotating = false;

  /**
   * 看视频
   * @returns {Promise<void>}
   */
  async onWatchToFreeTouch() {
    if (this.isRotating) {
      return;
    }
    if (model.user.msg.videoCount >= 3) {
      return WordsUtils.error('免费次数已经用完');
    }
    this.isRotating = true;
    const result = await wxUtils.showVideoAd()
    if (result) {
      const res = await apiUtils.luckyTurntable(4);
      model.user.msg.videoCount++;
      this.refreshVideoCount();
      await this.luckyTurntable.rotateOnceTo(res.index[0])
      this.showResult(res.index, false)
      this.initSkinShow()
      if (this.checkIsPowerful(res.index[0])) {
        this.flutterAction()
      }
    }
    this.isRotating = false;
  }

  async onDiamondRotateMoreTouch() {
    if (model.user.getItemNum(COMMON_CID.DIAMOND) < globalConfig.turntablecost.diamodscost10) {
      return WordsUtils.error('钻石不足')
    }
    const res = await apiUtils.luckyTurntable(3)
    await this.luckyTurntable.fastRotate(res.index)
    this.showResult(res.index)
    this.initSkinShow()
    if (this.checkIsPowerful(res.index[0])) {
      this.flutterAction()
    }
  }

  onGuideTouch() {
    cc.instantiate(this.probabilityPrefab).parent = cc.director.getScene()
  }

  onBack() {
    cc.director.loadScene('menu')
  }

  showResult(indexes: [number], isDiamond = true) {
    this.luckyResult.active = true
    this.luckyResult.getComponent(LuckyResult).setResultIndex(indexes, isDiamond)
    this.refreshLabelPowerful()
  }

  toMerge() {
    cc.director.loadScene('shop')
  }

  private flutterAction() {
    const node = new cc.Node()
    node.addComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(this.powerfulTexture)
    node.x = -264;
    node.y = 7;
    node.scaleX = 0.5
    node.scaleY = 0.5
    this.node.addChild(node)

    function runAction(node) {
      const action = cc.sequence([
        cc.moveTo(1, cc.v2(197, -210)),
        cc.fadeIn(0.6),
        cc.callFunc(() => {
          node.destroy()
        })
      ])
      node.runAction(action)
    }

    runAction(node)
  }

  private checkIsPowerful(index: number) {
    return index === 2 || index === 4 || index === 6 || index === 8
  }

  private refreshLabelPowerful() {
    this.labelPowerful.string = model.user.getItemNum(COMMON_CID.PIECE_POWERFUL).toString()
  }
}

